using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using MAPI;
using SharePoint.ImportExport.Core;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using Exchange.Export.DataHandler;


namespace Microsoft.SharePoint.Export.ExchangePublicFolders
{
	/// <summary>
	/// Summary description for folderPicker.
	/// </summary>
	public class folderPicker : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button btnOK;
		private System.Windows.Forms.Button btnCancel;
		private System.Windows.Forms.TreeView folderTree;
		private MAPI.Session mapiSession = null;
		private string StoreName="Public Folders";
		private string FolderRoot="";
		/// <summary>
		/// This is the selected folder
		/// </summary>
		public string SelectedFolder="";
		Exporter oExporter=null;
		object StoreID=null;
		int thislevel=0;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
		/// <summary>
		/// This is the constructor for the class
		/// </summary>
		/// <param name="folderRoot">This is the starting point</param>
		/// <param name="storeName">This is the name of the messagestore (Case sensitive)</param>
		/// <param name="MapiSession">This is the shared MAPI Session</param>

		public folderPicker(string folderRoot,string storeName,MAPI.Session MapiSession)
		{
			mapiSession=MapiSession;
			StoreName=storeName;
			
			FolderRoot=folderRoot;
			while(FolderRoot.EndsWith("\\"))
			{
				FolderRoot=FolderRoot.Substring(0,FolderRoot.Length-1);
			}
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btnOK = new System.Windows.Forms.Button();
			this.btnCancel = new System.Windows.Forms.Button();
			this.folderTree = new System.Windows.Forms.TreeView();
			this.SuspendLayout();
			// 
			// btnOK
			// 
			this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
			this.btnOK.Location = new System.Drawing.Point(8, 232);
			this.btnOK.Name = "btnOK";
			this.btnOK.TabIndex = 0;
			this.btnOK.Text = "OK";
			this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
			// 
			// btnCancel
			// 
			this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.btnCancel.Location = new System.Drawing.Point(192, 232);
			this.btnCancel.Name = "btnCancel";
			this.btnCancel.TabIndex = 1;
			this.btnCancel.Text = "Cancel";
			this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
			// 
			// folderTree
			// 
			this.folderTree.ImageIndex = -1;
			this.folderTree.Location = new System.Drawing.Point(8, 8);
			this.folderTree.Name = "folderTree";
			this.folderTree.SelectedImageIndex = -1;
			this.folderTree.Size = new System.Drawing.Size(272, 208);
			this.folderTree.Sorted = true;
			this.folderTree.TabIndex = 2;
			this.folderTree.BeforeSelect += new System.Windows.Forms.TreeViewCancelEventHandler(this.folderTree_BeforeSelect);
			// 
			// folderPicker
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(292, 266);
			this.Controls.Add(this.folderTree);
			this.Controls.Add(this.btnCancel);
			this.Controls.Add(this.btnOK);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
			this.Name = "folderPicker";
			this.Text = "Choose Folder";
			this.Load += new System.EventHandler(this.folderPicker_Load);
			this.ResumeLayout(false);

		}
		#endregion

		private void folderPicker_Load(object sender, System.EventArgs e)
		{
			PopulateList();
		
		}
		void PopulateList()
		{
			oExporter = new Exporter("",FolderRoot);
			object folderID=null;
			MAPI.Folders mapiFolders = oExporter.getFolders(mapiSession,StoreName,out folderID);
            if (null != mapiFolders)
            {
                FillTree(mapiFolders, null, 0);
            }
            Marshal.FinalReleaseComObject(mapiFolders);
			mapiFolders=null;
            oExporter.oSession.Logoff();
            Marshal.FinalReleaseComObject(oExporter.oSession);
			oExporter=null;

		}
		private void FillTree(MAPI.Folders folders,TreeNode node, int level)
		{
			int folderCount = (int)folders.Count;
			MAPI.Folder folder = (MAPI.Folder)folders.GetFirst();
			if(null==StoreID)
				StoreID=folder.StoreID;
			string tabs="";
			for(int j=0;j<level;j++)
				tabs+="\t";
			if(folderCount>500)
			{
				Logger.Log(ErrorLevel.Warning,"The folder chooser can only show 500 subfolders per folder");
				folderCount=500;
			}
			
			for (int i=1; i <= folderCount; i++)
			{
				Logger.Log(ErrorLevel.Information,tabs+"Processing folder "+folder.Name);
				try
				{
					TreeNode childNode=new TreeNode(folder.Name.ToString());
					childNode.Tag=folder.ID;
					//MAPI.Folders childFolders=(MAPI.Folders)folder.Folders;
                    if (null != node)
                    {
                        node.Nodes.Add(childNode);
                    }
                    else
                    {
                        folderTree.Nodes.Add(childNode);
                    }
				}
				catch(System.Runtime.InteropServices.COMException ex)
				{
					Logger.Log(ErrorLevel.Error,"Exception occurred: "+ex.Message);
				}
                Marshal.ReleaseComObject(folder);
				folder = (MAPI.Folder)folders.GetNext();

			}
		}

		private void btnOK_Click(object sender, System.EventArgs e)
		{
			TreeNode node=folderTree.SelectedNode;
			if(null!=node)
			{
				if(FolderRoot.Length>0)
					SelectedFolder=FolderRoot+"\\"+node.FullPath;
				else
					SelectedFolder=node.FullPath;
			}
			this.Close();

		}

		private void btnCancel_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}


		private void folderTree_BeforeExpand(object sender, System.Windows.Forms.TreeViewCancelEventArgs e)
		{
			
		
		}
	
		private void folderTree_BeforeSelect(object sender, System.Windows.Forms.TreeViewCancelEventArgs e)
		{
			TreeNode node=e.Node;
			if(null!=node)
			{
				if(node.GetNodeCount(false)==0)
				{
					object ID=node.Tag;
					MAPI.Folder folder=(MAPI.Folder)mapiSession.GetFolder(ID,StoreID);
					thislevel++;
					FillTree((MAPI.Folders)folder.Folders,node,thislevel);
                    Marshal.ReleaseComObject(folder);
					folder=null;
				}
			}
		
		}
	}
			

		
}

	